package com.fengye.security.jwt.process;

import com.auth0.jwt.interfaces.Claim;
import com.pearadmin.common.tools.jwt.Auth0JwtUtil;
import lombok.NonNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Token有效性验证拦截器
 */
@Slf4j
// @Component("jwtTokenFilter")
public class JwtTokenFilter extends OncePerRequestFilter {

    private final JwtUserDetailsService jwtUserDetailsService;
    // 白名单
    String[] whitelist = {"hello", "register", "login"};

    public JwtTokenFilter(@NonNull JwtUserDetailsService jwtUserDetailsService) {
        this.jwtUserDetailsService = jwtUserDetailsService;
    }

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        String path = httpServletRequest.getServletPath();
        log.info("JwtTokenFilter过滤器,{} 请求验证", path);
        for (String item : whitelist) {
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            if (antPathMatcher.match(item, path)) {
                log.info("白名单,'{}',直接放行", path);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                return;
            }
        }

        String authorization = httpServletRequest.getHeader("Authorization");

        if (StringUtils.hasLength(authorization) && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);

            try {
                // 反序列化token
                Map<String, Claim> verifyToken = Auth0JwtUtil.verify(token);
                assert verifyToken != null;
                Claim c = verifyToken.get("username");
                String username = c.toString();
                if (!StringUtils.hasText(username)) {
                    throw new AuthenticationServiceException("使用token认证失败");
                }

                log.info("token中的 username 为{}", username);

                // 获取用户的详细信息
                UserDetails user = jwtUserDetailsService.loadUserByUsername(username);//JSON.parseObject(claims.get("userDetails", String.class), JwtUserDetails.class);

                // 构建已经认证的登录用户信息
                JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(user, "", user.getAuthorities());
                jwtAuthenticationToken.setDetails(new WebAuthenticationDetails(httpServletRequest));

                // 关键: 在 spring security中声明已经存在了该用户信息,不会进行登录验证了.
                SecurityContextHolder.getContext().setAuthentication(jwtAuthenticationToken);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } catch (Exception exception) {
                SecurityContextHolder.clearContext();
                SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key",
                        "anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }
        }
        SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key",
                "anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

}